package com.bbb.zuul.filter;

import com.bbb.zuul.service.user.UserCenterService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.*;


public class DataAuthorityFilter extends ZuulFilter {

    @Autowired
    UserCenterService userCenterService;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        Integer status;
        Random random = new Random();
        status = random.nextInt(2);
        if(1 == status ) {
            context.setSendZuulResponse(true);// 对该请求进行路由
            context.setResponseStatusCode(200);
            context.set("dataAuthorityFilter", true);// 设值，让下一个Filter看到上一个Filter的状态

        }else{
            context.setSendZuulResponse(false);// 过滤该请求，不对其进行路由
            context.setResponseStatusCode(401);// 返回错误码
            //context.setResponseBody("{\"result\":\"username is not correct!\"}");// 返回错误内容
            context.set("dataAuthorityFilter", false);
        }
        Map<String, Object> ccc = userCenterService.getLoginStatus("ccc");

        HttpServletResponse response = context.getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> result = new HashMap<>();
        result.put("code", 401);
        result.put("msg", "no data author");
        String jsonStr = "";
        PrintWriter out = null;
        try {
            jsonStr = objectMapper.writeValueAsString(result);
            out = response.getWriter();
            out.write(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }
}
